/*
 * Project Name spring-boot-tools
 * File Name WSToolKit
 * Package Name com.huxiaosu.tools.mina.utils
 * Create Time 2024/5/25
 * Create by name：liujie
 */
package com.huxiaosu.tools.mina.utils;

import org.apache.mina.core.session.IoSession;

/**
 * Description
 *
 * @author liujie
 * @date 2024/5/25 13:22
 */
public class WSToolKit {
    private WSToolKit() {
    }

    public enum WSSessionState {
        /**websocket 握手*/
        WSHandshake,
        /**websocket 链接*/
        Connected;
        public final static String ATTRIBUTE_KEY = "__SESSION_STATE";
    }

    static <T> T nvl(T t1, T t2) {
        return t1 == null ? t2 : t1;
    }

    public static void setSessionState(IoSession session) {
        session.setAttribute(WSSessionState.ATTRIBUTE_KEY, WSSessionState.WSHandshake);

    }
    public static WSSessionState getSessionState(IoSession session) {

        return (WSSessionState) session.getAttribute(WSSessionState.ATTRIBUTE_KEY);
    }

    public static String getMessageColumnValue(String[] headers, String headerTag) {
        for (String header : headers) {
            if (header.startsWith(headerTag)) {
                return header.substring(headerTag.length()).trim();
            }
        }

        return null;
    }

    public static String subString(String src, int order, String flag) {
        for (int i = 1, j = 0, k = 0;; i++) {
            j = src.indexOf(flag, k);
            if (i < order) {
                if (j == -1) {
                    return "";
                } else {
                    k = j + 1;
                }
            } else {
                if (j == -1) {
                    return src.substring(k);
                } else {
                    return src.substring(k, j);
                }
            }
        }
    }

    @SuppressWarnings("AlibabaUndefineMagicConstant")
    public static int bytes2int(byte[] bytes){
        int result = 0;
        if(bytes.length == 4){
            int a = (bytes[0] & 0xff) << 24;
            int b = (bytes[1] & 0xff) << 16;
            int c = (bytes[2] & 0xff) << 8;
            int d = (bytes[3] & 0xff);
            result = a | b | c | d;
        }
        return result;
    }
}
